package com.playwright.controller;

import com.alibaba.fastjson.JSONObject;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.Locator;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.options.LoadState;
import com.playwright.entity.UnPersisBrowserContextInfo;
import com.playwright.utils.*;
import com.playwright.websocket.WebSocketClientService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;


@RestController
@RequestMapping("/api/browser")
@Tag(name = "AI登录登录控制器", description = "AI登录相关接口")
public class BrowserController {

    // 浏览器操作工具类
    @Autowired
    private ScreenshotUtil screenshotUtil;

    @Autowired
    private  WebSocketClientService webSocketClientService;

    @Value("${cube.url}")
    private String logUrl;


    @Autowired
    private LogMsgUtil logMsgUtil;

    @Autowired
    private BrowserUtil browserUtil;

    @Autowired
    private BaiduUtil baiduUtil;

    /**
     * 检查元宝主站登录状态
     * @param userId 用户唯一标识
     * @return 登录状态："false"表示未登录，手机号表示已登录
     */
    @Operation(summary = "检查元宝登录状态", description = "返回手机号表示已登录，false 表示未登录")
    @GetMapping("/checkLogin")
    public String checkYBLogin(@Parameter(description = "用户唯一标识")  @RequestParam("userId") String userId) throws InterruptedException {
        try {
            UnPersisBrowserContextInfo browserContextInfo = BrowserContextFactory.getBrowserContext(userId, 2);
            BrowserContext browserContext = browserContextInfo.getBrowserContext();
            Page page = browserContext.pages().get(0);
            page.navigate("https://yuanbao.tencent.com/chat/naQivTmsDa/");
            page.waitForLoadState(LoadState.LOAD);
            Thread.sleep(3000);
            Locator phone = page.locator("//p[@class='nick-info-name']");
            if (phone.count() > 0) {
                String phoneText = phone.textContent();
                if (phoneText.equals("未登录")) {
                    return "false";
                }
                return phoneText;
            } else {
                return "false";
            }
        } catch (Exception e) {
            throw e;
        }
    }




    /**
     * 获取代理版元宝登录二维码
     * @param userId 用户唯一标识
     * @return 二维码图片URL 或 "false"表示失败
     */
    @GetMapping("/getYBQrCode")
    @Operation(summary = "获取代理版元宝登录二维码", description = "返回二维码截图 URL 或 false 表示失败")
    public String getYBQrCode(@Parameter(description = "用户唯一标识") @RequestParam("userId") String userId) throws InterruptedException, IOException {
        try {
            UnPersisBrowserContextInfo browserContextInfo = BrowserContextFactory.getBrowserContext(userId, 2);
            BrowserContext context = null;
            if (browserContextInfo != null) {
                context = browserContextInfo.getBrowserContext();
            }
            Page page = context.pages().get(0);
            page.navigate("https://yuanbao.tencent.com/chat/naQivTmsDa");
            page.locator("//span[contains(text(),'登录')]").click();
            Thread.sleep(4000);
            boolean isLogin = false;
            String url = screenshotUtil.screenshotAndUpload(page,"checkYBLogin.png");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("url",url);
            jsonObject.put("userId",userId);
            jsonObject.put("type","RETURN_PC_YB_QRURL");
            webSocketClientService.sendMessage(jsonObject.toJSONString());
            Locator phone = page.locator("//p[@class='nick-info-name']");
            String phoneText = phone.textContent();
            for(int i = 0; i < 6; i++) {
//                每十秒刷新一次
                if(phoneText.contains("未登录")) {
                    Thread.sleep(10000);
                    url = screenshotUtil.screenshotAndUpload(page,"checkYBLogin.png");
                    jsonObject.put("url",url);
                    webSocketClientService.sendMessage(jsonObject.toJSONString());
                } else {
                    break;
                }
                phoneText = phone.textContent();
            }
            if(phone.count()>0){
                JSONObject jsonObjectTwo = new JSONObject();
                if(phoneText.contains("未登录")) {
                    jsonObjectTwo.put("status","false");
                } else {
                    isLogin = true;
                    jsonObjectTwo.put("status",phoneText);
                }
                jsonObjectTwo.put("userId",userId);
                jsonObjectTwo.put("type","RETURN_YB_STATUS");
                webSocketClientService.sendMessage(jsonObjectTwo.toJSONString());
            }
            return isLogin ? phoneText : "false";
        } catch (Exception e) {
            throw e;
        }
    }


    /**
     * 检查豆包登录状态
     * @param userId 用户唯一标识
     * @return 登录状态："false"表示未登录，手机号表示已登录
     */
    @Operation(summary = "检查豆包登录状态", description = "返回手机号表示已登录，false 表示未登录")
    @GetMapping("/checkDBLogin")
    public String checkDBLogin(@Parameter(description = "用户唯一标识") @RequestParam("userId") String userId) throws InterruptedException {
        try (BrowserContext context = browserUtil.createPersistentBrowserContext(false,userId,"db")) {
            Page page = browserUtil.getOrCreatePage(context);
            page.navigate("https://www.doubao.com/chat/");
            Thread.sleep(5000);
            Locator locator = page.locator("//*[@id=\"root\"]/div[1]/div/div[3]/div/main/div/div/div[1]/div/div/div/div[2]/div/button");
            if (locator.count() > 0 && locator.isVisible()) {
                return "false";
            } else {
                Thread.sleep(500);

                page.locator("[data-testid=\"chat_header_avatar_button\"]").click();
                Thread.sleep(500);
                page.locator("[data-testid=\"chat_header_setting_button\"]").click();
                Thread.sleep(500);
                Locator phone = page.locator(".nickName-cIcGuG");
                if(phone.count()>0){
                    String phoneText = phone.textContent();
                    return phoneText;
                }else{
                    return "false";
                }
            }
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 获取豆包登录二维码
     * @param userId 用户唯一标识
     * @return 二维码图片URL 或 "false"表示失败
     */
    @Operation(summary = "获取豆包登录二维码", description = "返回二维码截图 URL 或 false 表示失败")
    @GetMapping("/getDBQrCode")
    public String getDBQrCode(@Parameter(description = "用户唯一标识") @RequestParam("userId") String userId) throws InterruptedException, IOException {
        try (BrowserContext context = browserUtil.createPersistentBrowserContext(false,userId,"db")) {
            Page page = browserUtil.getOrCreatePage(context);
            page.navigate("https://www.doubao.com/chat/");
            Locator locator = page.locator("//*[@id=\"root\"]/div[1]/div/div[3]/div/main/div/div/div[1]/div/div/div/div[2]/div/button");
            Thread.sleep(2000);
            if (locator.count() > 0 && locator.isVisible()) {
                locator.click();
                page.locator("[data-testid='qrcode_switcher']").evaluate("el => el.click()");

                Thread.sleep(3000);
                String url = screenshotUtil.screenshotAndUpload(page,"checkDBLogin.png");

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("url",url);
                jsonObject.put("userId",userId);
                jsonObject.put("type","RETURN_PC_DB_QRURL");
                webSocketClientService.sendMessage(jsonObject.toJSONString());
                Locator login = page.getByText("登录成功");
                login.waitFor(new Locator.WaitForOptions().setTimeout(60000));
                Thread.sleep(5000);
                page.locator("[data-testid=\"chat_header_avatar_button\"]").click();
                Thread.sleep(1000);
                page.locator("[data-testid=\"chat_header_setting_button\"]").click();
                Thread.sleep(1000);
                Locator phone = page.locator(".nickName-cIcGuG");
                if(phone.count()>0){
                    String phoneText = phone.textContent();
                    JSONObject jsonObjectTwo = new JSONObject();
                    jsonObjectTwo.put("status",phoneText);
                    jsonObjectTwo.put("userId",userId);
                    jsonObjectTwo.put("type","RETURN_DB_STATUS");
                    webSocketClientService.sendMessage(jsonObjectTwo.toJSONString());
                }
            }
        } catch (Exception e) {
            throw e;
        }
        return "false";
    }

    /**
     * 退出腾讯元宝
     */
    @Operation(summary = "退出腾讯元宝登录状态", description = "执行退出操作，返回true表示成功")
    @GetMapping("/loginOut")
    public boolean loginOut(@Parameter(description = "用户唯一标识") @RequestParam("userId") String userId) throws InterruptedException {
        try (BrowserContext context = browserUtil.createPersistentBrowserContext(false,userId,"yb")) {
            Page page = browserUtil.getOrCreatePage(context);
            page.navigate("https://yuanbao.tencent.com/chat/naQivTmsDa");
            page.click("span.icon-yb-setting");
            page.click("text=退出登录");
            page.locator("//*[@id=\"hunyuan-bot\"]/div[2]/div/div[2]/div/div/div[3]/button[2]").click();
            Thread.sleep(3000);
            return true;
        } catch (Exception e) {
            throw e;
        }
    }

    @Operation(summary = "检查百度AI登录状态", description = "返回用户名/手机号表示已登录，false 表示未登录")
    @GetMapping("/checkBaiduLogin")
    public String checkBaiduLogin(@Parameter(description = "用户唯一标识") @RequestParam("userId") String userId) throws Exception {
        try (BrowserContext context = browserUtil.createPersistentBrowserContext(false, userId, "baidu")) {
            Page page = browserUtil.getOrCreatePage(context);

            // 使用BaiduUtil检查登录状态
            String loginStatus = baiduUtil.checkBaiduLogin(page, true);

            if (!"false".equals(loginStatus)) {
                return loginStatus; // 返回用户名或登录状态
            } else {
                return "false"; // 未登录
            }

        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 获取百度登录二维码
     * @param userId
     */
    @Operation(summary = "获取百度登录二维码", description = "返回二维码截图 URL 或 false 表示失败")
    @GetMapping("/getBaiduQrCode")
    public String getBaiduQrCode(@Parameter(description = "用户唯一标识") @RequestParam("userId") String userId) {
        try (BrowserContext context = browserUtil.createPersistentBrowserContext(false, userId, "baidu")) {
            Page page = browserUtil.getOrCreatePage(context);
            // 首先检查当前登录状态
            String currentStatus = baiduUtil.checkBaiduLogin(page, true);
            if (!"false".equals(currentStatus)) {
                // 已经登录，直接返回状态
                JSONObject statusObject = new JSONObject();
                statusObject.put("status", currentStatus);
                statusObject.put("userId", userId);
                statusObject.put("type", "RETURN_BAIDU_STATUS");
                webSocketClientService.sendMessage(statusObject.toJSONString());
                logMsgUtil.sendTaskLog("百度AI已登录，用户: " + currentStatus, userId, "百度AI");

                // 截图返回当前页面
                String url = screenshotUtil.screenshotAndUpload(page, "getBaiduLoggedIn.png");
                JSONObject qrUpdateObject = new JSONObject();
                qrUpdateObject.put("url", url);
                qrUpdateObject.put("userId", userId);
                qrUpdateObject.put("type", "RETURN_PC_BAIDU_QRURL");
                webSocketClientService.sendMessage(qrUpdateObject.toJSONString());
                return url;
            }

            // 未登录，使用BaiduUtil获取二维码
            String url = baiduUtil.waitAndGetQRCode(page, userId);

            if (url != null && !url.trim().isEmpty()) {
                // 发送二维码截图
                JSONObject qrUpdateObject = new JSONObject();
                qrUpdateObject.put("url", url);
                qrUpdateObject.put("userId", userId);
                qrUpdateObject.put("type", "RETURN_PC_BAIDU_QRURL");
                webSocketClientService.sendMessage(qrUpdateObject.toJSONString());

                // 实时监测登录状态 - 最多等待60秒
                int maxAttempts = 30; // 30次尝试，每次2秒
                for (int i = 0; i < maxAttempts; i++) {
                    Thread.sleep(2000);

                    // 检查当前页面登录状态
                    String loginStatus = baiduUtil.checkBaiduLogin(page, false);

                    if (!"false".equals(loginStatus)) {
                        // 登录成功，发送状态到WebSocket
                        JSONObject statusSuccessObject = new JSONObject();
                        statusSuccessObject.put("status", loginStatus);
                        statusSuccessObject.put("userId", userId);
                        statusSuccessObject.put("type", "RETURN_BAIDU_STATUS");
                        webSocketClientService.sendMessage(statusSuccessObject.toJSONString());

                        logMsgUtil.sendTaskLog("百度AI登录成功: " + loginStatus, userId, "百度AI");
                        break;
                    }

                    // 每5次尝试重新截图一次，可能二维码已更新
                    if (i % 5 == 4) {
                        try {
                            String newUrl = screenshotUtil.screenshotAndUpload(page, "getBaiduQrCode_refresh.png");
                            JSONObject qrRefreshObject = new JSONObject();
                            qrRefreshObject.put("url", newUrl);
                            qrRefreshObject.put("userId", userId);
                            qrRefreshObject.put("type", "RETURN_PC_BAIDU_QRURL");
                            webSocketClientService.sendMessage(qrRefreshObject.toJSONString());
                        } catch (Exception e) {
                            UserLogUtil.sendExceptionLog(userId, "获取百度AI二维码", "getBaiduQrCode", e, logUrl + "/saveLogInfo");
                        }
                    }
                }
                return url;
            } else {
                logMsgUtil.sendTaskLog("获取百度AI二维码失败", userId, "百度AI");
                // 发送失败消息到前端
                JSONObject errorObject = new JSONObject();
                errorObject.put("url", "");
                errorObject.put("userId", userId);
                errorObject.put("type", "RETURN_PC_BAIDU_QRURL");
                errorObject.put("error", "获取二维码失败");
                webSocketClientService.sendMessage(errorObject.toJSONString());
                return "false";
            }

        } catch (Exception e) {
            logMsgUtil.sendTaskLog("获取百度AI二维码失败", userId, "百度AI");
            // 发送异常消息到前端
            JSONObject errorObject = new JSONObject();
            errorObject.put("url", "");
            errorObject.put("userId", userId);
            errorObject.put("type", "RETURN_PC_BAIDU_QRURL");
            errorObject.put("error", "获取二维码异常");
            webSocketClientService.sendMessage(errorObject.toJSONString());
            UserLogUtil.sendExceptionLog(userId, "获取百度AI二维码", "getBaiduQrCode", e, logUrl + "/saveLogInfo");
            return "false";
        }
    }

    public void checkLogin(String number) {
    }
}